/* *
 * 通用公共js库，通用函数
 */

//获取上一页实例
const prePage = ()=>{
	let pages = getCurrentPages();
	let prePage = pages[pages.length - 2];
	return prePage.$vm;

}

// 根据多个名字筛选
export function filterByName(aim, nameArr, keyworld = 'fun_name') {
	if(Array.isArray(nameArr)){
		const result = []
		for(let i = 0; i < nameArr.length; i++) {
			aim.some(item => {
				if(item[keyworld] === nameArr[i]) {
					result.push(item)
				}
				return item.fun_name === nameArr[i]
			})
		}
		return result
	} else {
		console.log('第二个参数必须是数组');
	}

}



export function colorRgba(sHex, alpha = 0.6){
	
		// 十六进制颜色值的正则表达式
		let reg = /^#([0-9a-fA-f]{3}|[0-9a-fA-f]{6})$/
		/* 16进制颜色转为RGB格式 */
		let sColor = sHex.toLowerCase()
		if (sColor && reg.test(sColor)) {
		  if (sColor.length === 4) {
			let sColorNew = '#'
			for (let i = 1; i < 4; i += 1) {
			  sColorNew += sColor.slice(i, i + 1).concat(sColor.slice(i, i + 1))
			}
			sColor = sColorNew
		  }
		  //  处理六位的颜色值
		  let sColorChange = []
		  for (let i = 1; i < 7; i += 2) {
			sColorChange.push(parseInt('0x' + sColor.slice(i, i + 2)))
		  }
		  // return sColorChange.join(',')
		  // 或
		  let rgba =  'rgba(' + sColorChange.join(',') + ',' + alpha + ')'
		  return rgba
		} else {
		  return sColor
		}
}

// rgbTo 16


/**
 * Parse the time to string
 * @param {(Object|string|number)} time
 * @param {string} cFormat
 * @returns {string}
 */
export function parseTime(time, cFormat) {
  if (arguments.length === 0) {
    return null
  }
  if(time === '' || time === null || time === undefined) {
	  return null
  }
  const format = cFormat || '{y}-{m}-{d} {h}:{i}:{s}'
  let date
  if (typeof time === 'object') {
    date = time
  } else {
    if ((typeof time === 'string') && (/^[0-9]+$/.test(time))) {
      time = parseInt(time)
    }
    if ((typeof time === 'number') && (time.toString().length === 10)) {
      time = time * 1000
    }
    date = new Date(time)
  }
  const formatObj = {
    y: date.getFullYear(),
    m: date.getMonth() + 1,
    d: date.getDate(),
    h: date.getHours(),
    i: date.getMinutes(),
    s: date.getSeconds(),
    a: date.getDay()
  }
  const time_str = format.replace(/{(y|m|d|h|i|s|a)+}/g, (result, key) => {
    let value = formatObj[key]
    // Note: getDay() returns 0 on Sunday
    if (key === 'a') { return ['日', '一', '二', '三', '四', '五', '六'][value ] }
    if (result.length > 0 && value < 10) {
      value = '0' + value
    }
    return value || 0
  })
  return time_str
}

//获取url参数
export function getQueryObject(url) {
  url = url == null ? window.location.href : url
  const search = url.substring(url.lastIndexOf('?') + 1)
  const obj = {}
  const reg = /([^?&=]+)=([^?&=]*)/g
  search.replace(reg, (rs, $1, $2) => {
    const name = decodeURIComponent($1)
    let val = decodeURIComponent($2)
    val = String(val)
    obj[name] = val
    return rs
  })
  return obj
}

//统一消息弹框
const msg = (title, icon='none', duration=1500, mask=false)=>{
	//统一提示方便全局修改
	if(Boolean(title) === false){
		return;
	}
	uni.showToast({
		title,
		duration,
		mask,
		icon
	});
}
// 数组去重
export function arrayNonRepeatfy(arr) {
	let array = [];
    for(let i =0,obj = {}; i<arr.length; i++){
	  if(!obj[arr[i].skus_id]){
		 array.push(arr[i]);
		 obj[arr[i].skus_id] = true;
	  }
    }
  return array ;
}

/**克隆对象
 * @param {Object} source
 * @returns {Object}
 */


export function deepClone(source) {
  if (!source && typeof source !== 'object') {
    throw new Error('error arguments', 'deepClone')
  }
  const targetObj = source.constructor === Array ? [] : {}
  Object.keys(source).forEach(keys => {
    if (source[keys] && typeof source[keys] === 'object') {
      targetObj[keys] = deepClone(source[keys])
    } else {
      targetObj[keys] = source[keys]
    }
  })
  return targetObj
}

const Validate = {

  /**
   * 判断输入值是否为空
   */
  required(value) {
    if (typeof value === 'number') {
      value = value.toString()
    } else if (typeof value === 'boolean') {
      return !0
    }
    return value && value.length > 0
  },

  /**
   * 重复验证
   */
  noDuplicate(values) {
    for (let i = 0; i < values.length; i++) {
      for (let j = 0; j < values.length; j++) {
        if (values[i] == values[j] && i != j) {
          return false
        }
      }
    }
    return true
  },

  /**
   * 验证电子邮箱格式
   */
  email(value) {
    return /^[a-zA-Z0-9.!#$%&'*+\/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/.test(value)
  },

  /**
   * 验证手机格式
   */
  tel(value) {
    return /^1[234578]\d{9}$/.test(value)
  },

  /**
   * 验证电话格式
   */
  phone(value) {
    return /^0?(13[0-9]|15[012356789]|17[013678]|18[0-9]|14[57])[0-9]{8}$/.test(value)
  },

  /**
   * 验证联系方式（固话&手机）
   */
  call(value) {
    return /(^(0[0-9]{2,3}\-)?([2-9][0-9]{6,7})+(\-[0-9]{1,4})?$)|(^((\(\d{3}\))|(\d{3}\-))?(1[358]\d{9})$)/.test(value)
  },

  /**
   * 验证传真格式
   */
  fax(value) {
    return /^(\d{3,4}-)\d{7,8}$/.test(value)
  },

  /**
   * 验证URL格式
   */
  url(value) {
    return /^(?:(?:(?:https?|ftp):)?\/\/)(?:\S+(?::\S*)?@)?(?:(?!(?:10|127)(?:\.\d{1,3}){3})(?!(?:169\.254|192\.168)(?:\.\d{1,3}){2})(?!172\.(?:1[6-9]|2\d|3[0-1])(?:\.\d{1,3}){2})(?:[1-9]\d?|1\d\d|2[01]\d|22[0-3])(?:\.(?:1?\d{1,2}|2[0-4]\d|25[0-5])){2}(?:\.(?:[1-9]\d?|1\d\d|2[0-4]\d|25[0-4]))|(?:(?:[a-z\u00a1-\uffff0-9]-*)*[a-z\u00a1-\uffff0-9]+)(?:\.(?:[a-z\u00a1-\uffff0-9]-*)*[a-z\u00a1-\uffff0-9]+)*(?:\.(?:[a-z\u00a1-\uffff]{2,})).?)(?::\d{2,5})?(?:[/?#]\S*)?$/i.test(value)
  },

  /**
   * 验证日期格式
   */
  date(value) {
    return !/Invalid|NaN/.test(new Date(value).toString())
  },

  /**
   * 验证ISO类型的日期格式
   */
  dateISO(value) {
    return /^\d{4}[\/\-](0?[1-9]|1[012])[\/\-](0?[1-9]|[12][0-9]|3[01])$/.test(value)
  },

  /**
   * 验证十进制数字
   */
  number(value) {
    return /^(?:-?\d+|-?\d{1,3}(?:,\d{3})+)?(?:\.\d+)?$/.test(value)
  },

  /**
   * 验证整数
   */
  digits(value) {
    return /^\d+$/.test(value)
  },

  /**
   * 验证正整数
   */
  amount(value) {
    return /^[1-9]\d*$/.test(value)
  },

  /**
   * 验证身份证号码
   */
  idcard(value) {
    return /^[1-9]\d{5}[1-9]\d{3}((0\d)|(1[0-2]))(([0|1|2]\d)|3[0-1])\d{3}([0-9]|X)$/.test(value)
  },

  /**
   * 验证内容是否相同
   */
  equalTo(value, param) {
    return value == param
  },

  /**
   * 验证是否包含某个值
   */
  contains(value, param) {
    return value.indexOf(param) >= 0
  },

  /**
   * 验证最小长度
   */
  minlength(value, param) {
    return value.length >= param
  },

  /**
   * 验证最大长度
   */
  maxlength(value, param) {
    return value.length <= param
  },

  /**
   * 验证一个长度范围[min, max]
   */
  rangelength(value, param) {
    return (value.length >= param[0] && value.length <= param[1])
  },

  /**
   * 验证最小值
   */
  min(value, param) {
    return Number(value) >= Number(param)
  },

  /**
   * 验证最大值
   */
  max(value, param) {
    return Number(value) <= Number(param)
  },

  /**
   * 验证一个值范围[min, max]
   */
  range(value, param) {
    return (value >= param[0] && value <= param[1])
  }
}

// 防抖
export function _debounce(fn, delay) {

    var delay = delay || 200;
    var timer;
    return function () {
        var th = this;
        var args = arguments;
        if (timer) {
            clearTimeout(timer);
        }
        timer = setTimeout(function () {
            timer = null;
            fn.apply(th, args);
        }, delay);
    };
}
// 节流
export function _throttle(fn, interval) {
    var last;
    var timer;
    var interval = interval || 200;
    return function () {
        var th = this;
        var args = arguments;
        var now = +new Date();
        if (last && now - last < interval) {
            clearTimeout(timer);
            timer = setTimeout(function () {
                last = now;
                fn.apply(th, args);
            }, interval);
        } else {
            last = now;
            fn.apply(th, args);
        }
    }
}



/*
 * 核心方法，实现加减乘除运算，确保不丢失精度
 * 思路：把小数放大为整数（乘），进行算术运算，再缩小为小数（除）
 *
 * @param a {number} 运算数1
 * @param b {number} 运算数2
 * @param op {string} 运算类型，有加减乘除（add/subtract/multiply/divide）
 *
 */
const operation =  (a, b, op) => {
	/*
	 * 判断obj是否为一个整数
	 */
	function isInteger(obj) {
		return Math.floor(obj) === obj
	}
	
	/*
	 * 将一个浮点数转成整数，返回整数和倍数。如 3.14 >> 314，倍数是 100
	 * @param floatNum {number} 小数
	 * @return {object}
	 *   {times:100, num: 314}
	 */
	function toInteger(floatNum) {
		let ret = {times: 1, num: 0};
		if (isInteger(floatNum)) {
			ret.num = floatNum;
			return ret
		}
		let strfi = floatNum + '';
		let dotPos = strfi.indexOf('.');
		let len = strfi.substr(dotPos + 1).length;
		let times = Math.pow(10, len);
		let intNum = parseInt(floatNum * times + 0.5, 10);
		ret.times = times;
		ret.num = intNum;
		return ret
	}
	let o1 = toInteger(a);
	let o2 = toInteger(b);
	let n1 = o1.num;
	let n2 = o2.num;
	let t1 = o1.times;
	let t2 = o2.times;
	let max = t1 > t2 ? t1 : t2;
	let result = null;
	switch (op) {
		case 'add':
			if (t1 === t2) { // 两个小数位数相同
				result = n1 + n2
			} else if (t1 > t2) { // o1 小数位 大于 o2
				result = n1 + n2 * (t1 / t2)
			} else { // o1 小数位 小于 o2
				result = n1 * (t2 / t1) + n2
			}
			return result / max;
		case 'subtract':
			if (t1 === t2) {
				result = n1 - n2
			} else if (t1 > t2) {
				result = n1 - n2 * (t1 / t2)
			} else {
				result = n1 * (t2 / t1) - n2
			}
			return result / max;
		case 'multiply':
			result = (n1 * n2) / (t1 * t2);
			return result;
		case 'divide':
			result = (n1 / n2) * (t2 / t1);
			return result
	}
}

// 加减乘除的四个接口
export function add(a, b) {
	return operation(a, b, 'add')
}

export function subtract(a, b) {
	return operation(a, b, 'subtract')
}

export function multiply(a, b) {
	return operation(a, b, 'multiply')
}

export function divide(a, b) {
	return operation(a, b, 'divide')
}



const isArray = Array.isArray || function (obj) {  
    return obj instanceof Array;  
};  

export default {  
    vdata: Validate,
	prePage,
	msg
}

